package com.xfcy.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xfcy.blog.common.R;
import com.xfcy.blog.common.constant.Constant;
import com.xfcy.blog.common.constant.SqlConstant;
import com.xfcy.blog.common.enums.PublishEnum;
import com.xfcy.blog.common.enums.ResultCode;
import com.xfcy.blog.dto.DictDataDTO;
import com.xfcy.blog.entity.Dict;
import com.xfcy.blog.mapper.DictDataMapper;
import com.xfcy.blog.entity.DictData;
import com.xfcy.blog.mapper.DictMapper;
import com.xfcy.blog.service.DictDataService;
import com.xfcy.blog.service.DictService;
import com.xfcy.blog.utils.BeanCopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (DictData)表服务实现类
 *
 * @author 晓风残月Lx
 * @since 2023-04-09 11:03:05
 */
@Service("dictDataService")
public class DictDataServiceImpl extends ServiceImpl<DictDataMapper, DictData> implements DictDataService {

    @Autowired
    private DictMapper dictMapper;


    /**
     * 根据字典类型获取字典数据
     * @param types
     * @return
     */
    @Override
    public R getDataByDictType(List<String> types) {
        if (types == null || types.size() == 0) {
            return R.success();
        }

        Map<String, Map<String, Object>> hashMap = new HashMap<>();

        // 从Dict中查出对应的id集合
        List<Dict> dictList = dictMapper.selectList(new QueryWrapper<Dict>()
                .in(SqlConstant.TYPE, types)
                .eq(SqlConstant.IS_PUBLISH, PublishEnum.PUBLISH.getCode()));

        // 从DictData中查处dict_id对应的
        dictList.forEach(item -> {
            List<DictData> dictDataList = baseMapper.selectList(new QueryWrapper<DictData>()
                    .eq(SqlConstant.DICT_TYPE_ID, item.getId())
                    .eq(SqlConstant.IS_PUBLISH, PublishEnum.PUBLISH.getCode())
                    .orderByDesc(SqlConstant.SORT));

            String defaultValue = null;
            for (DictData dictData : dictDataList) {
                //选取默认值
                if (Constant.STRING_ONE.equals(dictData.getIsDefault())){
                    defaultValue = dictData.getValue();
                    break;
                }
            }
            Map<String, Object> result = new HashMap<>();
            result.put(Constant.DEFAULT_VALUE, defaultValue);
            result.put(Constant.LIST, dictDataList);
            hashMap.put(item.getType(),result);
        });
        return R.success(hashMap);
    }

    /**
     * 字典数据列表
     * @param pageNo
     * @param pageSize
     * @param dictId
     * @return
     */
    @Override
    public R listDictData(Integer pageNo, Integer pageSize, Integer dictId) {
        QueryWrapper<DictData> queryWrapper = new QueryWrapper<DictData>()
                .eq(dictId != null && !dictId.equals(Constant.ZERO),SqlConstant.DICT_TYPE_ID, dictId);
        Page<DictData> data = baseMapper.selectPage(new Page<>(pageNo, pageSize), queryWrapper);
        data.getRecords().forEach(item -> {
            Dict dict = dictMapper.selectById(item.getDictId());
            item.setDict(dict);
        });
        return R.success(data);
    }

    /**
     * 添加字典数据
     * @param dictDataDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R add(DictDataDTO dictDataDTO) {
        // 判断添加的字典数据是否在
        isExist(dictDataDTO);
        DictData dictData = BeanCopyUtil.copyObject(dictDataDTO, DictData.class);
        baseMapper.insert(dictData);
        return R.success();
    }

    /**
     * 修改字典数据
     * @param dictDataDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R update(DictDataDTO dictDataDTO) {
        DictData dictData = baseMapper.selectOne(new QueryWrapper<DictData>().eq(SqlConstant.DICT_LABEL, dictDataDTO.getLabel()));
        if (dictData != null && !dictData.getId().equals(dictDataDTO.getId())) {
            return R.error("该标签已存在");
        }
        DictData data = BeanCopyUtil.copyObject(dictDataDTO, DictData.class);
        baseMapper.updateById(data);
        return R.success();
    }

    /**
     * 批量删除字典数据
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteBatchDictData(List<Long> ids) {
        baseMapper.deleteBatchIds(ids);
        return R.success();
    }

    /**
     * 删除字典数据
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteDictData(Long id) {
        baseMapper.deleteById(id);
        return R.success();
    }





    // 自定义方法
    private void isExist(DictDataDTO dictDataDTO) {
        DictData temp = baseMapper.selectOne(new QueryWrapper<DictData>()
                .eq(SqlConstant.DICT_LABEL, dictDataDTO.getLabel())
                .eq(SqlConstant.DICT_TYPE_ID, dictDataDTO.getDictId())
                .last(SqlConstant.LIMIT_ONE));
        Assert.isNull(temp, ResultCode.DATA_TAG_IS_EXIST.getDesc());
    }
}


